import api from '@/common/api.js'
import {
  mapState
} from 'vuex'

// var globalTimer = null
export default {
  computed: {
    ...mapState({
      loginUser: state => state.$loginUser,
      userInfo: state => state.$userInfo,
      storeInfo: state => state.$storeNo,
      isLogin: state => state.$isLogin,
      curStoreNo: state => state.$storeNo, //当前店铺编号
      curMemberInfo: state => state?.$curMember || null, //当前选择的会员
      staffList: state => state?.$staffList || [],
      memberList: state => state.$memberList || [], //会员列表
      curAssistant: state => state.$curAssistant, //当前选择的营业员
      goodsViewMode: state => state.$goodsViewMode, //首页页面商品展示样式 图文or文字
      onLockScreen: state => state.$onLockScreen,
      $lockScreenSettings: state => state.$lockScreenSettings,
      $userMenuList: state => state.$userMenuList
    }),
    menuAuth() {
      const authObj = {}
      if (Array.isArray(this.$userMenuList) && this.$userMenuList.length > 0) {
        this.$userMenuList.forEach(menu => {
          authObj[menu.fk_menu_no] = menu.fk_menu_name
        })
      }
      return authObj
    },
    // 营业员
    staffAssistantList() {
      return this.staffList.filter(item => item.business_status === '是')
    },
    tenantInfo() {
      if (Array.isArray(this.loginUser?.tenantInfos) && this.loginUser?.tenantInfos.length > 0) {
        return this.loginUser?.tenantInfos[0]
      }
    },
    $api() {
      return api
    },
  },
  data() {
    return {
      updateTime: null,
      curDate: null,
      curTime: null,
      pageUUID: '',
      _pageScrollTop: 0,
      setPageTitle: "",
    }
  },
  onShow(option) {
    if (option?.query?.title) {
      this.setPageTitle = option?.query?.title
    }
  },
  async onLoad(option) {
    if (option.title) {
      this.setPageTitle = option.title
    }
    this.pageUUID = uni.$u.guid(20)
  },
  methods: {
    navigateBack() {
      uni.navigateBack()
    },
    renderStr(str, obj = {}) {
      obj = {
        ...this.globalVariable,
        ...obj
      }

      const buildResult = (key, result) => {
        if (key && key.indexOf('||') !== -1) {
          let arr = key.split('||')
          console.log(arr);
          result = arr.reduce((pre, cur) => {
            if (!pre) {
              pre = buildResult(cur, result)
            }
            return pre
          }, '')
        } else {
          let arr = key.split('.')
          if (arr.length > 1) {
            arr.forEach(item => {
              try {
                result = result[item] ?? '';
                if (result === 0) {
                  result = '0'
                }
              } catch (e) {
                //TODO handle the exception
              }
            })
          }
        }
        return result

      }


      if (typeof obj === 'object' && str && typeof str === 'string') {
        str = str.replace(/\$\{(.*?)\}/g, (match, key) => {
          key = key.trim()
          let result = obj[key]
          if (key === 'today') {
            result = dayjs().format("YYYY-MM-DD")
          } else {
            result = buildResult(key, obj)
          }

          // let arr = key.split('.')
          // if (arr.length > 1) {
          //   result = obj
          //   arr.forEach(item => {
          //     try {
          //       result = result[item] ?? '';
          //       if (result === 0) {
          //         result = '0'
          //       }
          //     } catch (e) {
          //       //TODO handle the exception
          //     }
          //   })
          // }
          return result
        })
      }
      return str
    },

    downloadFile(e) {
      return new Promise((resolve) => {
        uni.showLoading({
          title: "下载中..."
        })
        uni.downloadFile({
          url: this.getImagePath(e, true), //仅为示例，并非真实接口地址。
          complete: (e) => {
            uni.hideLoading()
            if (e?.tempFilePath) {
              resolve(e.tempFilePath)
            } else {
              uni.showToast({
                title: '下载失败！',
                icon: 'none'
              })
              resolve(false)
            }
          }
        });
      })
    },
    async saveFile(e) {
      if (e) {
        let tempFilePath = await this.downloadFile(e)
        if (tempFilePath) {
          uni.saveFile({
            tempFilePath: tempFilePath,
            success: function(res) {
              var savedFilePath = res.savedFilePath;
              uni.showModal({
                title: "提示",
                content: `文件已保存到${savedFilePath}`,
                showCancel: false,
                success: (e) => {
                  if (e.confirm) {
                    uni.getSavedFileList({
                      success: function(f) {
                        console.log(f.fileList);
                        uni.showModal({
                          title: 'fileList',
                          content: JSON.stringify(f.fileList)
                        })
                      }
                    });
                  }
                }
              })
            }
          });
        }
      }
    },


    toTop() {
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 300,
        success: () => {
          this.reachBottomnum = 1
        },
      });
    },
    getwxMchId() {
      // 获取商户号
      return this.storeInfo?.wx_mch_id || this.$api?.wxMchId || '1485038452'
    },
    getServiceName(srv) {
      let len = srv.lastIndexOf('_');
      let serviceName = srv.slice(0, len) + '_';
      if (this.srvType === 'list' || this.srvType === 'detail') {
        serviceName += 'select';
      } else {
        serviceName += this.srvType;
      }
      return serviceName;
    },

    async handleAfterSubmit(handler, effect_data) {
      const self = this
      const afterSubmit = handler;
      if (Array.isArray(afterSubmit) && afterSubmit.length > 0) {
        const globalData = {
          data: effect_data || {},
          storeInfo: self.storeInfo,
          userInfo: self.userInfo,
          storeUser: self.vstoreUser
        }
        const actionResult = new Array(afterSubmit.length)
        for (let i = 0; i < afterSubmit.length; i++) {
          let item = afterSubmit[i];
          if ((i > 0 && actionResult[i - 1]) || i == 0) {
            if (effect_data && effect_data.id && ['redirectTo', 'navigateTo'].includes(item.type)) {
              if (item.url) {
                let url = this.renderStr(item.url, globalData)
                uni[item.type]({
                  url: url,
                  success: () => {
                    actionResult[i] = true
                  }
                })
              }
            } else if (item.type === 'wx_pay') {
              if (item.money_col && item.order_no_col && effect_data && effect_data[
                  item.order_no_col]) {
                const totalMoney = effect_data[item.money_col] || 0
                if (totalMoney == 0) {
                  actionResult[i] = true
                } else {
                  const wxMchId = this.getwxMchId()
                  const orderData = {
                    order_no: effect_data[item.order_no_col]
                  }
                  const result = await this.toPlaceOrder(totalMoney * 100, '',
                    orderData, wxMchId);
                  if (result && result.prepay_id) {
                    let res = await this.getPayParams(result.prepay_id, wxMchId);
                    const resData = await new Promise((resolve) => {
                      wx.requestPayment({
                        timeStamp: res.timeStamp.toString(),
                        nonceStr: res.nonceStr,
                        package: res.package,
                        signType: 'MD5',
                        paySign: res.paySign,
                        success(res) {
                          // 支付成功
                          resolve(true)
                        },
                        fail(res) {
                          // 支付失败/取消支付
                          resolve('支付失败/取消支付')
                        }
                      });
                    })
                    actionResult[i] = resData
                  }
                }
              } else {
                actionResult[i] === true
              }
            } else if (item.type === 'update_call_back') {
              if (item.service && item.app && Array.isArray(item.data) && item
                .cond) {
                let url = this.getServiceUrl(item.app, item.service, 'operate');
                let req = [{
                  serviceName: item.service,
                  condition: [],
                  data: item.data
                }]
                if (Array.isArray(item.cond)) {
                  req[0].condition = item.cond.map(c => {
                    c.value = self.renderStr(c.value, globalData)
                    return c
                  })
                }
                const res = await self.$http.post(url, req);
                if (res.data.state == 'SUCCESS') {
                  actionResult[i] = true
                } else {
                  actionResult[i] = res.data.resultMessage
                }
              }
            } else if (item.type === 'toDetail') {
              if (item.trigger) {
                if (item.trigger.type == 'condition') {
                  let isPass = true;
                  if (Array.isArray(item.trigger?.rule) && item.trigger.rule.length > 0) {
                    item.trigger.rule.forEach(a => {
                      a = JSON.parse(this.renderStr(JSON.stringify(a), globalData))
                      if (a.result && a.value === a.result) {

                      } else {
                        isPass = false
                      }
                    })
                  }
                  if (isPass === false) {
                    return
                  }
                }
              }

              this.srvType = 'detail'

              let serviceName = this.addV2?.select_service_name || this.colV2?.select_service_name || this
                .getServiceName(this.serviceName)
              let fieldsCond = [{
                column: 'id',
                value: effect_data.id,
                display: false
              }]
              let url =
                `/publicPages/formPage/formPage?type=detail&serviceName=${serviceName}&fieldsCond=${encodeURIComponent(JSON.stringify(this.fieldsCond))}`
              if (this.appName) {
                url += `&appName=${this.appName}`
              }

              if (item.hideChildTable) {
                url += `&hideChildTable=true`
              }

              if (item.custom_url) {
                url = this.renderStr(item.custom_url, globalData);
              }

              if (item.view_cfg) {
                url += `&view_cfg=${encodeURIComponent(JSON.stringify(item.view_cfg))}`
              }

              uni.redirectTo({
                url
              })
              actionResult[i] = true
            }
          }
        }
        if (actionResult.length === afterSubmit.length && !actionResult.every(item =>
            item == true)) {
          self.srvType === 'detail'
          self.srvType === 'use_type'
          self.formButtons = []
        } else {
          actionResult.forEach(item => {
            if (item && typeof item === 'string') {
              uni.showModal({
                title: "提示",
                content: item,
                showCancel: false
              })
            }
          })
        }
        return actionResult
      }
    }
  }
}
